package com.tanhua.server.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.NearUserVo;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜附近 业务处理层
 */
@Service
public class LocationService {

    @Reference
    private UserLocationApi userLocationApi;

    @Reference
    private UserInfoApi userInfoApi;

    /**
     * 上报地理位置
     * //纬度 113.929778
     * //经度 22.582111
     */
    public void addLocation(Double latitude, Double longitude, String addrStr) {
        Long userId = UserHolder.getUserId();//当前登录用户id
        if (latitude < longitude) {
            userLocationApi.addLocation(longitude, latitude, userId, addrStr);
        } else {
            //正常逻辑走此行代码
            userLocationApi.addLocation(latitude, longitude, userId, addrStr);
        }
    }

    /**
     * 搜附近
     */
    public List<NearUserVo> searchNearUser(String gender, String distance) {
        Long userId = UserHolder.getUserId();//当前登录用户id
        //a.根据当前登录用户id 和 距离 搜索附近用户  （没有区别性别 以及 包含自己）
        //将 List<UserLocation> 转为 List<UserLocationVo>
        List<UserLocationVo> locationVoList = userLocationApi.searchNearUser(userId, distance);
        if (locationVoList == null || locationVoList.size() == 0) {
            //如果没有数据，可以造假数据
            return null;
        }
        //b.查询UserInfo
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo userLocationVo : locationVoList) {
            Long ulUserId = userLocationVo.getUserId();
            //过滤自己
            if (ulUserId.equals(userId)) {
                continue;
            }
            //根据ulUserId 查询UserInfo
            UserInfo userInfo = userInfoApi.findByUserId(ulUserId);
            //根据性别条件来过滤
            if (!userInfo.getGender().equals(gender)) {
                continue;
            }
            NearUserVo nearUserVo = new NearUserVo();
            nearUserVo.setNickname(userInfo.getNickname());//昵称
            nearUserVo.setAvatar(userInfo.getAvatar());//头像
            nearUserVo.setUserId(ulUserId);//用户id
            nearUserVoList.add(nearUserVo);
        }
        //c.返回VO
        return nearUserVoList;
    }
}
